package com.hfengxiang.example.canvasrotatedemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

public class ScreenRotateView extends View {
    private Matrix mMatrix;
    private Paint paint;
    private Bitmap bitmap;
    private float currentScale;
    private float degree;
    private float centerX;
    private float centerY;

    public ScreenRotateView(Context context) {
        this(context,null);
    }

    public ScreenRotateView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,-1);
    }

    public ScreenRotateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        bitmap = Utils.getPhoto(getResources(), getResources().getDisplayMetrics().widthPixels);
        mMatrix = new Matrix();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(getWidth() / 2f, getHeight() / 2f);
        canvas.rotate(degree);
        Log.i("Hfx", "w=" + getWidth() / 2f + ",h=" + getHeight() / 2f);
        canvas.drawBitmap(bitmap, mMatrix, paint);
    }

    public void setProgress(float fraction, float centerX, float centerY,float r) {
        degree = fraction * r;
        this.centerX = centerX;
        this.centerY = centerY;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        currentScale = ScaleCalculator.calculateScale(getWidth(), getHeight(), bitmap.getWidth(), bitmap.getHeight(), 0);
        mMatrix.postTranslate(-bitmap.getWidth() / 2f, -bitmap.getHeight() / 2f);
        mMatrix.postScale(currentScale, currentScale);
    }
}
